<template>
    <el-select :placeholder='placeholder' filterable remote :clearable='props.clearable' :size='props.size' :loading='state.loading' :remote-method='remoteMethod' v-model='props.modelValue' @change='change'>
    <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
        >
    </el-option>
    </el-select>
</template>

<script lang='ts' setup>
    import { reactive, ref, watch } from "vue"

    const props = withDefaults(defineProps<{
        modelValue : any[],
        level? : number,
        valueField? : string,
        labelField? : string,
        loadFunc : {
            asyn (key:string) : Promise<any[]>
        },
        size? : string,
        initQuery? : string,
        clearable? : boolean,
        placeholder? : string
    }>(), {
        valueField : 'id',
        labelField : 'name',
        level : 3,
        size : 'small',
        clearable : true,
        placeholder : '请输入'
    })

    const emit = defineEmits<{
        (e : 'change', value : any) : void,
        (e : 'update:modelValue', any)
    }>()

    const state = reactive({
        loading : false
    })

    const value = ref(props.modelValue)

    const options = reactive<any[]>([])

    async function remoteMethod(query:string) {
        if(state.loading) return
        console.log(query)
       if(query !== '') {
           state.loading = true
           options.splice(0)
           const rows = await props.loadFunc(query)
           state.loading = false
           options.push(...rows.map(row => ({value : row[props.valueField], label : row[props.labelField]})))
       }
    }

    function change(e) {
        console.log(e)
        emit('update:modelValue', e)
        emit('change', e)
    }


    watch(() => props.initQuery, (query) => {
        console.log('5444444444')
        console.log(query)
        if(query) {
            remoteMethod(query)
        }
    })

    
</script>